package com.example.demo.Service;

import com.example.demo.Dao.CrawlData;
import com.example.demo.Model.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Component
public class Analyze implements InitializingBean {

    public static List<RegionStats> allCoronaVirusData;

    static {
        allCoronaVirusData=new ArrayList<>();
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        allCoronaVirusData= Analyze.getAllCoronaVirusData();
        System.out.println("获取数据");
    }

    public static List<RegionStats> getAllCoronaVirusData() throws IOException {
        List<RegionStats> all=new ArrayList<>();
        CrawlData crawlData=new CrawlData();
        InputStream date=crawlData.getData();
        Reader in = new InputStreamReader(date);
        Iterable<CSVRecord> records = CSVFormat.DEFAULT.withFirstRecordAsHeader()
                .withDelimiter(',')
                .withQuote('"')
                .withRecordSeparator("\r\n")
                .withIgnoreEmptyLines(true)
                .withAllowDuplicateHeaderNames(true)
                .parse(in);
        for(CSVRecord csvRecord : records){
            String province=csvRecord.get("Province/State");
            String country=csvRecord.get("Country/Region");
            String total=csvRecord.get(csvRecord.size()-1);
            String per=csvRecord.get(csvRecord.size()-2);
            int t=Integer.parseInt(total);
            int p=Integer.parseInt(per);
            int a=t-p;
            RegionStats regionStats=new RegionStats(province,country,t,a);
            all.add(regionStats);
        }
        return all;
    }

}
